package com.elias.share.config;

import com.elias.share.enums.WebResultMsgEnum;
import com.elias.share.exception.BusinessException;
import com.elias.share.utils.WebResultUtil;
import com.elias.share.vo.WebResultVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.naming.SizeLimitExceededException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

@Log4j2
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(value = {SizeLimitExceededException.class, MaxUploadSizeExceededException.class})
    public <T> WebResultVo<T> largeFilesError() {
        log.info("file size limit exceeded");
        return WebResultUtil.fail(WebResultMsgEnum.FILE_SIZE_EXCEED_LIMIT.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public <T> WebResultVo<T> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
//        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return WebResultUtil.fail(WebResultMsgEnum.PARAM_ERROR.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public <T> WebResultVo<T> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//        String message = e
//                .getBindingResult()
//                .getAllErrors()
//                .stream()
//                .map(DefaultMessageSourceResolvable::getDefaultMessage)
//                .collect(Collectors.joining());
        return WebResultUtil.fail(WebResultMsgEnum.PARAM_ERROR.getMessage());
    }

    @ExceptionHandler(value = BusinessException.class)
    public <T> WebResultVo<T> handleBusinessException(BusinessException e) {
        return WebResultUtil.error(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public <T> WebResultVo<T> handleException(Exception e) {
        return WebResultUtil.error(WebResultMsgEnum.SYSTEM_ERROR.getMessage());
    }
}
